package com.shop.front.service.store;

import com.alibaba.fastjson.JSON;
import com.shop.front.vo.store.StoreCategoryVo;
import com.shop.front.dao.store.StoreCategorySQLDao;
import com.shop.web.cache.RedisCache;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class StoreCategoryService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private StoreCategorySQLDao storeCategorySQLDao;

    public BaseResponse menu() {
        List<StoreCategoryVo> firstCategoryList = null;

        // 首页缓存key
        int cacheTime = 3600;  // 秒
        String cacheKey = "category_menu";
        // 缓存是否存在
        String cacheVal = redisCache.getString(cacheKey);
        if(StringUtils.isNotBlank(cacheVal)) {
            firstCategoryList = JSON.parseObject(cacheVal, List.class);
            return new BaseResponse(firstCategoryList);
        }

        firstCategoryList = new ArrayList<>();

        Map<Long, StoreCategoryVo> categoryMap = new HashMap<>();

        StoreCategoryVo pidStoreCategory = null;
        List<StoreCategoryVo> categoryList = storeCategorySQLDao.findList();
        for (StoreCategoryVo category : categoryList) {
            categoryMap.put(category.getId(), category);

            if(null == category.getPid() || 0 == category.getPid()) {
                firstCategoryList.add(category);
            } else {
                pidStoreCategory = categoryMap.get(category.getPid());
                if(null == pidStoreCategory) {
                    continue;
                }

                pidStoreCategory.getChildCategoryList().add(category);
            }
        }

        // 缓存返回值
        redisCache.set(cacheKey, JSON.toJSONString(firstCategoryList), cacheTime);

        return new BaseResponse(firstCategoryList);
    }
}
